import LogModule from "./LogModule";

const {ccclass, property} = cc._decorator;

@ccclass
export default class HttpModule {

    static tokenKey: string = '';
    
    static quest (option) {
        return new Promise((resolve, reject) => {
            var url = 'http://api.tushare.pro';
            var method = option.method;
            var params = option.params;
            params.token = this.tokenKey;
            var timeout = option.timeout || 0;
            var xhr = new XMLHttpRequest();
            (timeout > 0) && (xhr.timeout = timeout);
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    if (xhr.status >= 200 && xhr.status < 400) {
                        var result:any = JSON.parse(xhr.responseText);
                        if (result.code == 0) {
                            let data = result.data;
                            setTimeout(() => {
                                resolve(data);
                            }, 60);
                        } else {
                            LogModule.log('http quest error, code = '+ result.code + ', msg = ' + result.msg);
                            reject('http quest error, code = '+ result.code + ', msg = ' + result.msg);
                        }
                    } else {
                        LogModule.log('http error, code = '+ xhr.status);
                        reject('http error, code = '+ xhr.status);
                    }
                }
            }.bind(this);
            xhr.open(method, url, true);
            let data = JSON.stringify(params);
            xhr.send(data);
            xhr.ontimeout = function () {
                LogModule.log('http ontimeout, code = '+ xhr.status);
                reject('http ontimeout, code = '+ xhr.status);
            };
        });
    }

    static get(params: Object) {
        var option = {
            params: params,
            method: 'get',
        };
        
        return this.quest(option);
    }

    static post(params: Object) {
        var option = {
            params: params,
            method: 'post',
        };
        
        return this.quest(option);
    }

    static async postAsync (params: Object) {
        var option = {
            params: params,
            method: 'post',
        };
        let data: any = await this.quest(option);
        let fields = data.fields;
        let items = data.items;
        let list = [];
        for (let index = 0; index < items.length; index++) {
            const item = items[index];
            let stock = {};
            for (let j = 0; j < fields.length; j++) {
                stock[fields[j]] = item[j];
            }
            list.push(stock);
        }
        
        return list;   
    }

}
